package com.sharecode.stock.task;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.sharecode.stock.service.MailService;
import com.sharecode.stock.service.StockCodeService;
import com.sharecode.stock.service.StockHistoryDataService;
import com.sharecode.stock.service.StockHistoryDateService;
import com.sharecode.stock.service.StockHistoryService;
import com.sharecode.stock.strategy.CalculateHandle;
import com.sharecode.stock.utils.DateUtils;
import com.sharecode.stock.utils.StockDataUtils;
import com.sharecode.stock.vo.MailBean;
import com.sharecode.stock.vo.stock.StockCode;
import com.sharecode.stock.vo.stock.StockHistory;
import com.sharecode.stock.vo.stock.StockHistoryData;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class StockTask {
	public static final List<MailBean> MAIL_BEANS = new ArrayList<>();
	@Autowired
	private StockCodeService stockCodeService;
	@Autowired
	private StockHistoryService stockHistoryService;
	@Autowired
	private StockHistoryDateService stockHistoryDateService;
	@Autowired
	private MailService mailService;
	@Autowired
	private StockHistoryDataService stockHistoryDataService;
	@Value(value = "${spring.profiles.active}")
	private String active;

	/**
	 * 拉去历史数据， 星期12345，并计算
	 */
	@Scheduled(cron = "0 33 19 * * *")
	public void taskHistoryData() {
		int week = DateUtils.week();
		// 7星期六 1 星期日
		if (week == 1 || week == 7) {
			return;
		}
		List<StockCode> list = new ArrayList<>();
		String date = stockHistoryDateService.find().getDate().replace("-", "");
		List<StockCode> stockCodes = stockCodeService.getAll();

		List<StockHistory> stockHistories = new ArrayList<>();
		String createDate = DateUtils.format();
		for (StockCode stockCode : stockCodes) {
			try {
				String code = stockCode.getCode();
				List<StockHistory> histories = StockDataUtils.getStockHistories(stockCode.getType() + code, date);
				if (CollectionUtils.isNotEmpty(histories)) {
					for (StockHistory history : histories) {
						history.setCode(code);
						history.setCycle(1);
					}
					stockHistoryService.save(histories);

					stockHistories.addAll(histories);

				}else {
					TimeUnit.SECONDS.sleep(1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		List<StockHistoryData> stockHistoryDatas = new ArrayList<>();
		for (StockCode stockCode : list) {
			try {
				String code = stockCode.getCode();
				List<StockHistory> histories = StockDataUtils.getStockHistories(stockCode.getType() + code, date);
				if (CollectionUtils.isNotEmpty(histories)) {
					for (StockHistory history : histories) {
						history.setCode(code);
						history.setCycle(1);
						stockHistoryDatas.add(new StockHistoryData(code, history.getDate(), 1, createDate));
					}
					stockHistoryService.save(histories);

					stockHistories.addAll(histories);

				} else {
					stockHistoryDatas.add(new StockHistoryData(code, date, 0, createDate));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		new Thread(() -> stockHistoryDataService.saveAll(stockHistoryDatas)).start();

		stockHistoryDateService.update();
		log.info("task处理数据完成,size->{}", stockHistories.size());
		// 内存不够
		if ("prd".equals(active)||"dev".equals(active)) {
			return;
		}

		if (CollectionUtils.isNotEmpty(stockHistories)) {
			for (StockHistory stockHistory : stockHistories) {
				CalculateHandle.handle(stockHistory);
			}
		}
	
		log.info("发送邮件,股票数量:{}", MAIL_BEANS.size());
		if (!MAIL_BEANS.isEmpty()) {
			try {
				StringBuffer buffer = new StringBuffer();
				for (MailBean mailBean : MAIL_BEANS) {
					buffer.append("【").append(mailBean.getSubject()).append("】").append(mailBean.getContent())
							.append("\n");
				}
				MailBean mailBean = new MailBean("【股票】通知", buffer.toString());
				mailBean.setBcc(true);
				mailService.sendSimpleMail(mailBean);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				MAIL_BEANS.clear();
			}
		}

	}
}
